package com.service;

import com.bean.Article;
import com.bean.Comment;
import com.github.pagehelper.PageHelper;
import com.mapper.ArticleMapper;
import com.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import java.sql.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static com.tool.Tool.getUserId;

/**
 * Created by Yuicon on 2017/3/20.
 */
@Service
public class ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CommentMapper commentMapper;


    /**
     * 文章列表
     * @return
     */
    public List<Article> findAll(int page) {
        PageHelper.startPage(page,5);
        return articleMapper.findAll();
    }

    /**
     * 某用户的文章列表
     * @param page
     * @param request
     * @return
     */
    public List<Article> findByUserId(int page, ServletRequest request) {
        PageHelper.startPage(page,5);
        return articleMapper.findByUserId(getUserId(request));
    }

    /**
     * 获取单篇文章
     *
     * @param id
     * @return
     */
    public Article findOne(String id) {
        Article article = articleMapper.findById(id);
        article.setComments(commentMapper.findByArticleId(id));
        return article;
    }

    /**
     * 添加文章
     *
     * @param article
     * @param req
     * @return
     */
    public int insert(Article article, ServletRequest req) {
        article.setId(UUID.randomUUID().toString());
        article.setUserId(getUserId(req));
        return articleMapper.insert(article);
    }

    /**
     * 删除文章
     *
     * @param articleId
     * @param req
     * @return
     */
    public int deleteById(String articleId, ServletRequest req) {
        Optional<Article> article = Optional.ofNullable(findOne(articleId));
        if (article.isPresent()) {
            if (article.orElseGet(Article::new).getUserId().equals(getUserId(req))) {
                return articleMapper.deleteById(articleId);
            }
        }
        return 0;
    }

    /**
     * 添加评论
     * @param comment
     * @param req
     * @return
     */
    public int addComment(Comment comment, ServletRequest req) {
        comment.setCreateTime(new Date(new java.util.Date().getTime()));
        comment.setId(UUID.randomUUID().toString());
        comment.setUserId(getUserId(req));
        return commentMapper.insert(comment);
    }
}
